package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.feign.english.IFeiEnglishFeignClient;
import com.xmy.cultivate.mapper.StudentAccountMapper;
import com.xmy.cultivate.respons.ResStudentAccount;
import com.xmy.cultivate.respons.ResStudentClassType;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2023-07-15
 */
@Service
public class StudentAccountServiceImpl extends ServiceImpl<StudentAccountMapper, StudentAccount> implements IStudentAccountService {


    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    @Lazy
    IFeiEnglishFeignClient iFeiEnglishFeignClient;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    StudentAccountMapper studentAccountMapper;

    @Autowired
    IMqPushService iMqPushService;



    public StudentAccount getOneForStudentId(Long studentId){
        return studentAccountMapper.getOneForStudentId(studentId);
    }


    @Override
    public Result updateAccount(Long studentId){
        Student student = iStudentService.getById(studentId);
        Quarter quarterNow = iQuarterService.getNowQuarter();
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("year_part",quarterNow.getYearPart());
        studentGradeQueryWrapper.eq("quarter_num",quarterNow.getNum());
        //studentGradeQueryWrapper.in("subjects_id",1,2);
        studentGradeQueryWrapper.eq("lesson_type",1);
        //studentGradeQueryWrapper.last("limit 1");
        studentGradeQueryWrapper.ne("status",3);
        studentGradeQueryWrapper.eq("student_id",studentId);
        studentGradeQueryWrapper.orderByDesc("id");
        studentGradeQueryWrapper.groupBy("student_id","subjects_id");
        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        List<String> subjectsNameList = new ArrayList<>();
        for (StudentGrade studentGrade:studentGradeList){
            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            Course course = iCourseService.getById(grade.getCourseId());
            String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(course.getSubjectsId().toString()));
            iMqPushService.updateStudentAccount(grade.getYearPart(),grade.getQuarterNum(),studentGrade.getStudentId(),studentGrade.getSubjectsId());
            subjectsNameList.add(subjectsName);
        }

        //没有存在查看预分班
        if (studentGradeList.size() == 0){
            studentGradeQueryWrapper = new QueryWrapper<>();
            //studentGradeQueryWrapper.in("subjects_id",1,2);
            studentGradeQueryWrapper.eq("lesson_type",1);
            //studentGradeQueryWrapper.last("limit 1");
            studentGradeQueryWrapper.ne("status",3);
            studentGradeQueryWrapper.eq("student_id",studentId);
            studentGradeQueryWrapper.eq("reading_status",0);
            studentGradeQueryWrapper.orderByDesc("id");
            studentGradeQueryWrapper.groupBy("student_id","subjects_id");
            studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
            for (StudentGrade studentGrade:studentGradeList){
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                Course course = iCourseService.getById(grade.getCourseId());
                String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(course.getSubjectsId().toString()));
                iMqPushService.updateStudentAccount(grade.getYearPart(),grade.getQuarterNum(),studentGrade.getStudentId(),studentGrade.getSubjectsId());
                subjectsNameList.add(subjectsName);
            }
        }

        if (subjectsNameList.size()>0){
             String subjectsNames = subjectsNameList.stream().collect(Collectors.joining(","));
             Result rs = new Result(Code.OK,"","成功更新了科目："+subjectsNames+"帐号");
             return rs;
        }else {
            return new Result(Code.ERROR,"",student.getName()+":未分班");
        }
    }

    /**
     * 报名添加学员帐号
     * @return
     */
    @Override
    public Result applyAddStudentAccount(Long schoolId, Long studentId, Long gradeId, Long courseId){
        try{
            Student student = iStudentService.getById(studentId);
            Quarter quarter = iQuarterService.getNowQuarter();

            QueryWrapper<StudentAccount> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("student_id",student.getId());
            accountQueryWrapper.last("limit 1");
            StudentAccount studentAccount = this.getOne(accountQueryWrapper);
            Course course = iCourseService.getById(courseId);
            Grade gradeNew = null;
            gradeNew = iGradeService.getById(gradeId);
            if (gradeNew == null){
                return new Result(Code.ERROR,"","更新失败：未分班");
            }
            //不等于英语，或者不等于精品课直接返回
            if (!course.getSubjectsId().equals(1L) || !gradeNew.getLessonType().equals(1)){
                return new Result(Code.ERROR,"","更新失败：未分班");
            }

            if (studentAccount == null){
                studentAccount = new StudentAccount();

                studentAccount.setId(idWorker.nextId());
                studentAccount.setSchoolId(schoolId);
                studentAccount.setStudentId(student.getId());
                studentAccount.setStudentName(student.getName());
                studentAccount.setStatus(1);
                studentAccount.setAccountType(1);
                studentAccount.setAddType(1);
                studentAccount.setYearPart(gradeNew.getYearPart());
                studentAccount.setQuarterNum(gradeNew.getQuarterNum());
                studentAccount.setGradeId(gradeId);
                //studentAccount.setYearClassId(gradeNew.getYearClassId().getKey());

                if (gradeNew!=null){
                    studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
                    studentAccount.setYearPart(gradeNew.getYearPart());
                }

                studentAccount.setYearClassId(course.getYearClassId().getKey());
                studentAccount.setQuarterNum(course.getQuarterNum());
                String account = this.getAccountStr(studentId,student.getName(),student.getIdCardNo(),student.getLinkmanPhone());
                studentAccount.setAccount(account);
                studentAccount.setPwd(account);
                this.save(studentAccount);
            }else {
                if (gradeNew!=null){
                    studentAccount.setSchoolId(schoolId);
                    studentAccount.setClassTypeId(gradeNew.getCourseTypeId());//班型
                    studentAccount.setGradeId(gradeNew.getId());
                    studentAccount.setYearPart(gradeNew.getYearPart());
                    studentAccount.setQuarterNum(gradeNew.getQuarterNum());
                    studentAccount.setYearClassId(course.getYearClassId().getKey());
                    studentAccount.setGradeId(gradeId);
                }
                this.updateById(studentAccount);
            }

            try{
                //转为map
                //Map map = BeanMapUtils.beanToMap(studentAccount);
                /*ResStudentAccount resStudentAccount = new ResStudentAccount();
                BeanUtils.copyProperties(studentAccount,resStudentAccount);
                if (gradeNew!=null){
                    resStudentAccount.setTeacherId(gradeNew.getTeacherId());
                    resStudentAccount.setGradeSection(CommonUtil.getGradeSection(gradeNew.getYearClassId().getKey()));
                }
                iFeiEnglishFeignClient.addAccount(resStudentAccount);*/

                iMqPushService.updateStudentAccount(gradeNew.getYearPart(),gradeNew.getQuarterNum(),studentId,course.getSubjectsId());

                //更新班型
                this.updateClassType(gradeNew.getYearPart(),course.getQuarterNum(),course.getSubjectsId(),studentId);
            }catch (Exception e){
                return new Result(Code.ERROR,"","更新失败："+e.getMessage());
            }
            return new Result(Code.OK,"","更新成功");
        }catch (Exception e){
            return new Result(Code.ERROR,"","更新失败："+e.getMessage());
        }
    }


    public String getAccountStr(Long studentId,String studentName,String idCardNo,String linkmanPhone){
        String str = "";
        if(StringUtils.isNotBlank(idCardNo)){
            if(idCardNo.length() == 18){
                str = idCardNo.substring(8, 12);
            }
        }else{
            if (StringUtils.isNotBlank(linkmanPhone)&& linkmanPhone.length()==11){
                str = linkmanPhone.substring(7, 11);
            }
        }
        if (StringUtils.isBlank(str)){
            Random random = new Random();
            str = String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);
        }
        String chinese = studentName;  // 要转换的中文字符串
        String pinyin = CommonUtil.chToPinyin(chinese);

        String account = pinyin + str;
        QueryWrapper<StudentAccount> studentAccountQueryWrapper = new QueryWrapper<>();
        studentAccountQueryWrapper.eq("account",account);
        studentAccountQueryWrapper.ne("student_id",studentId);
        Long count = studentAccountMapper.selectCount(studentAccountQueryWrapper);
        if (count>0){
            Random random = new Random();
            str = String.valueOf(random.nextInt(9999 - 1000 + 1) + 1000);
            account = pinyin + str;
        }
        account = account.replace("u:", "v");
        return account;
    }




    /**
     * 更新智能课班型
     * @return
     */
    @Override
    public void updateClassType(Integer yearPart, Integer quarterNum, Long subjectsId, Long studentId){
        if (subjectsId.equals(1L)){
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("year_part",yearPart);
            studentGradeQueryWrapper.eq("quarter_num",quarterNum);
            studentGradeQueryWrapper.eq("subjects_id",subjectsId);
            studentGradeQueryWrapper.eq("student_id",studentId);
            studentGradeQueryWrapper.eq("lesson_type",1);
            studentGradeQueryWrapper.eq("is_last",1);
            studentGradeQueryWrapper.last("limit 1");
            StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
            if (studentGrade != null){
                this.updateClassTypeForStudentGrade(studentGrade);
            }
        }
    }

    /**
     * 更新智能课班型
     * @return
     */
    @Async("onlineAsync")
    @Override
    public void updateClassTypeForStudentGrade(StudentGrade studentGrade){
        if (studentGrade != null){
            if (studentGrade.getSubjectsId().equals(1L)){
                Grade gradeNew = iGradeService.getById(studentGrade.getGradeId());
                ResStudentClassType resStudentClassType = new ResStudentClassType();
                resStudentClassType.setSchoolId(gradeNew.getSchoolId());
                resStudentClassType.setStudentId(studentGrade.getStudentId());
                resStudentClassType.setGradeId(gradeNew.getId());
                resStudentClassType.setTeacherId(gradeNew.getTeacherId());
                resStudentClassType.setYearPart(gradeNew.getYearPart());
                resStudentClassType.setQuarterNum(studentGrade.getQuarterNum());
                resStudentClassType.setClassTypeId(gradeNew.getCourseTypeId());
                resStudentClassType.setYearClassId(gradeNew.getYearClassId().getKey());
                resStudentClassType.setGradeSection(CommonUtil.getGradeSectionForYearClassId(gradeNew.getYearClassId().getKey()));
                resStudentClassType.setReadingStatus(studentGrade.getReadingStatus().getKey());
                iFeiEnglishFeignClient.updateStudentClassType(resStudentClassType);
            }
        }
    }


    /**
     * 修改了班级后
     * @param
     * @return
     */
    public boolean updateClassTypeForGrade(Grade grade){
        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
        studentGradeQueryWrapper.eq("grade_id",grade.getId());
        List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
        for (StudentGrade studentGrade:studentGradeList){
            try {
                //iFeiEnglishFeignClient.updateStudentClassType();
                ResStudentClassType studentClassType = new ResStudentClassType();
                studentClassType.setClassTypeId(grade.getCourseTypeId());
                studentClassType.setStudentId(studentGrade.getStudentId());
                studentClassType.setSchoolId(studentGrade.getSchoolId());
                studentClassType.setYearClassId(grade.getYearClassId().getKey());
                studentClassType.setGradeId(studentGrade.getGradeId());
                studentClassType.setQuarterNum(studentGrade.getQuarterNum());
                studentClassType.setYearPart(studentGrade.getYearPart());
            }catch (Exception e){

            }
        }
        return true;
    }

    @Override
    public String getAccountByStudentId(Long studentId) {
        return studentAccountMapper.getAccountByStudentId(studentId);
    }
}
